﻿using MovieTheaterApp.DataModels;
using MovieTheaterApp.Db.IDataAdapters.Interfaces;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MovieTheaterApp.Db.IDataAdapters.Adapters
{
    public class MovieAdapter : IMovieAdapter
    {
        public List<Movie> GetAllMovies()
        {
            List<Movie> movies;
            using (ApplicationDbContext db = new ApplicationDbContext())
            {
                movies = db.Movies.OrderBy(x => x.Title).ToList();
            }
            return movies;
        }
        public Movie GetMovie(int id)
        {
            Movie movie;
            using (ApplicationDbContext db = new ApplicationDbContext())
            {
                movie = db.Movies.Include("Reviews").Where(x => x.Id == id).FirstOrDefault();

            }
            return movie;
        }
        public Movie AddMovie(Movie movie)
        {
            using (ApplicationDbContext db = new ApplicationDbContext())
            {
                movie = db.Movies.Add(movie);
                db.SaveChanges();

            }
            return movie;
        }


        public Movie UpdateMovie(Movie movie)
        {
            using (ApplicationDbContext db = new ApplicationDbContext())
            {
                Movie oldmovie = db.Movies.Find(movie.Id);
                oldmovie.setProps(movie);
                db.SaveChanges();
            }
            return movie;
        }

        public void DeleteMovie(int id)
        {
            using (ApplicationDbContext db = new ApplicationDbContext())
            {
                Movie movie = db.Movies.Find(id);
                db.Movies.Remove(movie);
                db.SaveChanges();

            }
        }
        public List<Actor> GetActorsForMovie(int movieId)
        {
            List<Actor> actors = new List<Actor>();
            using (ApplicationDbContext db = new ApplicationDbContext())
            {
                //Get to intermediate Table
                List<ActorMovie> ams = db.ActorMovies.Where(x => x.MovieId == movieId).ToList();
                //Loop over the intermediateTable
                foreach (var am in ams)
                {
                    actors.Add(db.Actors.Where(x => x.Id == am.ActorId).FirstOrDefault());
                }

            }
            return actors;
        }
    }
}
